package com.central.utils

import java.sql.Timestamp
import java.text.SimpleDateFormat
import java.util.Date

import scala.util.Try

class DateFormat(time:String) {

  val hyphenType = raw"(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})".r
  val slashType = raw"(\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2})".r
  val periodType = raw"(\d{4}.\d{2}.\d{2} \d{2}:\d{2}:\d{2})".r
  val nothingType = raw"(\d{4}\d{2}\d{2}\d{2}\d{2}\d{2})".r

  def parse : Timestamp = {
    if(hyphenType.findFirstIn(time).isDefined)
      Hyphen.toTimestamp(time)
    else if(slashType.findFirstIn(time).isDefined)
      Slash.toTimestamp(time)
    else if(periodType.findFirstIn(time).isDefined)
      Period.toTimestamp(time)
    else if(nothingType.findFirstIn(time).isDefined)
      Nothing.toTimestamp(time)
    else
      new Timestamp(0L)
  }

}

object DateFormat {
  private val transfer:(Either[Date,Timestamp])=>String = (date)=>{
    val foramt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    val time = date.fold(d=>new Date(d.getTime), t=>new Date(t.getTime))
    foramt.format(time)
  }
  def toTimestamp(time:String):Timestamp = new DateFormat(time).parse
  def toDate(time:String):Date = new Date(new DateFormat(time).parse.getTime)
  def dateToString(time:Date):String = transfer(Left(time))
  def timestampToString(time:Timestamp):String = transfer(Right(time))
}

sealed trait DateType extends Product with Serializable {
  def toTimestamp(time:String):Timestamp
  protected def tryThisFormat(format:String, dateString:String) = Try(new SimpleDateFormat(format).parse(dateString))
}

final case object Hyphen extends DateType {
  override def toTimestamp(time: String): Timestamp = {
    val date = tryThisFormat("yyyy-MM-dd HH:mm:ss",time).getOrElse(new Date())
    new Timestamp(date.getTime)
  }
}

final case object Slash extends DateType {
  override def toTimestamp(time: String): Timestamp = {
    val date = tryThisFormat("yyyy/MM/dd HH:mm:ss",time).getOrElse(new Date())
    new Timestamp(date.getTime)
  }
}

final case object Period extends DateType {
  override def toTimestamp(time: String): Timestamp = {
    val date = tryThisFormat("yyyy.MM.dd HH:mm:ss",time).getOrElse(new Date())
    new Timestamp(date.getTime)
  }
}

final case object Nothing extends DateType {
  override def toTimestamp(time: String): Timestamp = {
    val date = tryThisFormat("yyyyMMddHHmmss",time).getOrElse(new Date())
    new Timestamp(date.getTime)
  }
}

